/*
 * 关闭当前窗口。（只适用于微信） 
 */
// 关闭当前窗口 开始
function closepage() {
	if (typeof WeixinJSBridge != "undefined") {
		WeixinJSBridge.call('closeWindow');
	}
}

function onBridgeReady() {
	if (typeof WeixinJSBridge != "undefined") {
		WeixinJSBridge.call('hideOptionMenu');
	}
}

if (typeof WeixinJSBridge == "undefined") {
    if( document.addEventListener ) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
} else {
    onBridgeReady();
}
//关闭当前窗口 结束

!function() { // 扩展js对象
	//时间格式
	Date.prototype.format = function(format) {
	    var o =
	    {
	        "M+" : this.getMonth()+1, //month
	        "d+" : this.getDate(),    //day
	        "h+" : this.getHours(),   //hour
	        "m+" : this.getMinutes(), //minute
	        "s+" : this.getSeconds(), //second
	        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
	        "S" : this.getMilliseconds() //millisecond
	    }
	    if(/(y+)/.test(format))
	    format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
	    for(var k in o)
	    if(new RegExp("("+ k +")").test(format))
	    format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
	    return format;
	}
	String.prototype.format=function() {  // alert("js实现用自符串替换占位符{0} {1} {2}".format("I", "LOVE", "YOU"));  
	  if(arguments.length==0) return this;  
	  for(var s=this, i=0; i<arguments.length; i++)  
	    s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);  
	  return s;  
	};
}();

/**
 * weknow core api
 */
var WeKnow = (function() {
	
	/**
	 * private function
	 */
	function hashCode(input) {
		var I64BIT_TABLE =
			'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'.split('');
		return function(input) {
			var hash = 5381;
			var i = input.length - 1;
			if(typeof input == 'string'){
				for (; i > -1; i--)
					hash += (hash << 5) + input.charCodeAt(i);
			}
			else{
				for (; i > -1; i--)
					hash += (hash << 5) + input[i];
				}
			var value = hash & 0x7FFFFFFF;
			var retValue = '';
			do {
				retValue += I64BIT_TABLE[value & 0x3F];
			}
			while(value >>= 6);
			return retValue;
		}(input);
	}

	/**
	 * public funciton
	 */
	function getRealPath() {
		//获取当前网址，如： http://localhost:8083/myproj/view/my.jsp
	  	var curWwwPath = window.document.location.href;
	  	//获取主机地址之后的目录，如： myproj/view/my.jsp
	  	var pathName = window.document.location.pathname;
	  	
		//获取主机地址，如： http://localhost:8083
		var pos = curWwwPath.indexOf(pathName);
	  	var localhostPath = curWwwPath.substring(0,pos);
	  	
		//获取带"/"的项目名，如：/myproj
		var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
	  	
		//得到了 http://localhost:8083/myproj
		
//		/***
//		 * 生产环境中 url 没有项目名称（2dEnterpriseManage），特此做如下讨巧处理
//		 */
//		if (localhostPath.indexOf('www') > -1) { // 生产环境
//			return localhostPath;
//		} else { // 开发环境
//			return localhostPath + projectName;
//		}
	
		return localhostPath + projectName;
	}
	
	function include(file) {
		var files = typeof file == "string" ? [file] : file; 
		for (var i = 0; i < files.length; i++) {
			var name = files[i].replace(/^\s|\s$/g, ""); 
			var att = name.split('.'); 
			var ext = att[att.length - 1].toLowerCase(); 
			var isCSS = ext == "css"; 
			var tag = isCSS ? "link" : "script"; 
			var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' "; 
			var link = (isCSS ? "href" : "src") + "='" + getRealPath() + name + "'"; 
			if ($(tag + "[" + link + "]").length == 0) $("head").prepend("<" + tag + attr + link + "></" + tag + ">"); 
		} 
	} 
	
	// 交换dom元素
	function swap($dom1, $dom2) {
		var $temobj1 = $("<div></div>");
	    var $temobj2 = $("<div></div>");
	    $temobj1.insertBefore($dom1);
	    $temobj2.insertBefore($dom2);
	    $dom1.insertAfter($temobj2);
	    $dom2.insertAfter($temobj1);
	    $temobj1.remove();
	    $temobj2.remove();
	}
	
	function scrollTo(domId, offset, f) {
		$("html, body").animate(
			{
			  scrollTop: ($(domId).offset().top + offset) + "px"
			},
			'slow',
			'swing',
			f
		);
	}
	
	/**
	 * 页面submit post
	 */
	function submit(action, params) {
		loading({opacity: 1});
		var form = document.createElement("form");   
	    document.body.appendChild(form);
	  	form.method = 'POST';
		form.action = action;
		for(key in params) {
			var input = document.createElement("input");
			input.type = "hidden"; 
		  	input.name = key; 
		  	input.value = params[key];
			form.appendChild(input);
		}
	    form.submit();
	}
	
	/**
	 * 页面迁移 get
	 * @param url
	 */
	function location(url, params) {
		loading({opacity: 1});
		if (!$.isEmptyObject(params)) {
			var firstParam = true;
			for(key in params) {
				if (firstParam && url.indexOf('?') == -1) {
					url += "?";
				} else {
					url += "&";
				}
				url += key + "=" + params[key];
				firstParam = false;
			}
		}
		window.location.href=url;
	}
	
	
	/**
	 * 显示加载中
	 */
	function loading(options) {
		var opacity = 0.5;// default
		if ('undefined' != typeof options && options.opacity != null) opacity = options.opacity;
		var $animationload = $('body div.animationload');
		if ($animationload.length) {
			$animationload.css('opacity', opacity).show().find('div.loader').show();
		} else {
			$('<div class="animationload" style="opacity: ' + (opacity ? opacity : 1) + ';"><div class="loader"></div></div>').appendTo('body');
		}
	}
	/**
	 * 取消显示加载中
	 */
	function closeLoading(speed) {
		var $animationload = $('body div.animationload');
		if ($animationload.length) {
//			$animationload.find('div.loader').delay(('undefined' != typeof speed && speed === 'slow' ? 200 : 0)).fadeOut();
//			$animationload.delay(('undefined' != typeof speed && speed === 'slow' ? 400 : 0)).fadeOut("slow");
			$animationload.find('div.loader').delay(('undefined' != typeof speed && speed === 'slow' ? 200 : 0)).fadeOut();
			$animationload.delay(('undefined' != typeof speed && speed === 'slow' ? 400 : 0)).fadeOut("slow", function() {
				$animationload.remove();
			});
		}
	}
	
	function layerMsg(msg, options) {
		var msgLength = msg.length;
		if ('undefined' === typeof msg || !msgLength) return;
		if (msgLength < 10) {
			if (!('time' in options)) options.time = 1500;
		} else if (msgLength < 20) {
			if (!('time' in options)) options.time = 2500;
		} else {
			if (!('time' in options)) options.time = 5000;
		}
		layer.msg(msg, options);
	}
	function successMsg(msg, options) {
		if ('undefined' === typeof options) options = {icon:1};
		layerMsg(msg, options);
	}
	
	function errorMsg(msg, options) {
		if ('undefined' === typeof options) options = {icon:2};
		layerMsg(msg, options);
	}
	
	function notifyMsg(msg, options) {
		if ('undefined' === typeof options) options = {icon:7};
		layerMsg(msg, options);
	}
	
	function systemMsg(msg, options) {
		if ('undefined' === typeof options) options = {icon:7, time: 10000};
		try {
            throw new Error();
        } catch (e) {
            var loc = e.stack.replace(/Error\n/).split(/\n/)[1].replace(/^\s+|\s+$/, "");
            msg += '<br>' + loc;
        }
		layerMsg(msg, options);
	}
	
	/**
	 * modal
	 */
	function modal(params) {
		if ('undefined' !== typeof params) {
			
			var $modal = $('div.confirm_dialog');
			if ($modal.length) { // 已经存在的话，删除重建
				$modal.remove();
			}
			
			var e = '';
			e += '<div class="wn_weui_dialog_confirm confirm_dialog">';
				e += '<div class="wn_weui_mask"></div>';
				e += '<div class="wn_weui_dialog">';
					e += '<div class="wn_weui_dialog_hd"><strong class="weui_dialog_title">';
						if ('undefined' !== typeof params.title && params.title.length) {
							e += params.title;
						}
					e += '</strong></div>';
					e += '<div class="wn_weui_dialog_bd">' + params.message + '</div>';
					e += '<div class="wn_weui_dialog_ft">';
					e == '</div>';
				e == '</div>';
			e == '</div>';
			
			$modal = $(e).appendTo($("body"));
			
			if ('undefined' === typeof params.buttons || !params.buttons.length) {
				$modal.find("div.modal-footer").remove();
			} else {
				$.each(params.buttons, function(idx, btn) {
					var bTxt = '<a href="javascript:;" class="wn_weui_btn_dialog ' + (btn.class != null ? btn.class : 'defualt') + '">' + btn.name + '</a>';
					$(bTxt).appendTo($modal.find("div.wn_weui_dialog_ft")).on("click", btn.onClick)
				});
			}
			
			return $modal;
		}
	}
	function closeModal() {
		var $modal = $('div.confirm_dialog');
		if ($modal.length) {
			$modal.remove();
		}
	}
	/**
	 * 确认dialog
	 */
	function confirm(message, callbackOK) {
		modal(
			{
				title: '确认',
				message:message,
				buttons:[
					{name:'取消', class:'default',
						onClick: function() {
			        		closeModal();
			        	}
					},
			        {name:'确认', class:'primary',
			        	onClick: function() {
			        		if ('function' === typeof callbackOK) callbackOK();
			        		closeModal();
			        	}
			        }
				]
			}
		);
	}
	
	/**
	 * 参数+url 组件新url
	 */
	function buildUrl(url, params) {
		if ('undefined' !== typeof params) {
			var firstParam = true;
			for(key in params) {
				if (firstParam && url.indexOf('?') == -1) {
					url += "?";
				} else {
					url += "&";
				}
				url += key + "=" + params[key];
				firstParam = false;
			}
		}
		return url;
	}
	
	
	return {
		 include: include // 动态加载js、css文件
		,swap: swap // 交换dom元素位置
		,scrollTo: scrollTo // 移动位置
		,buildUrl: buildUrl // 组装url
		,getRealPath: getRealPath//绝对路径
		
		/**
		 * 页面提交
		 */
		,location: location // 页面跳转 GET
		,submit: submit // 页面跳转 POST
		/**
		 * 加载中
		 */
		,loading: loading // 加载中
		,closeLoading: closeLoading // 关闭加载中
		
		/**
		 * 消息提示
		 */
//		,notify: notify // 通知
//		,autoHideNotify: autoHideNotify // 通知，5s自动隐藏
		,errorMsg: errorMsg
		,successMsg: successMsg
		,notifyMsg: notifyMsg
		,systemMsg: systemMsg
		
		/**
		 * 确认窗口
		 */
		,modal: modal // modal窗口
		,closeModal: closeModal // 关闭modal窗口
		,confirm: confirm // 确认modal窗口
	}
})();


$(document).ready(function() {
	// 动态加载
	// 通知plugins
//	WeKnow.include('/plugins/notifications/notification.css');
//	WeKnow.include('/plugins/notifyjs/dist/notify.min.js');
//	WeKnow.include('/plugins/notifications/notify-metro.js');
//	WeKnow.include('/plugins/notifications/notifications.js');
	
	WeKnow.include('/plugins/layer-v3.0.3/skin/default/layer.css');
	WeKnow.include('/plugins/layer-v3.0.3/layer.js');
	
	// 取消loading
	WeKnow.closeLoading('slow');
});

/* ios 回退时，加载中无法隐藏 bug 20170417 start*/
var u = navigator.userAgent, app = navigator.appVersion;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if (isiOS) {
	window.addEventListener("popstate", function(e) {
		WeKnow.closeLoading();

		//window.history.back();
		//在历史记录中后退,这就像用户点击浏览器的后退按钮一样。

		//window.history.go(-1);
		//你可以使用go()方法从当前会话的历史记录中加载页面（当前页面位置索引值为0，上一页就是-1，下一页为1）。

		//self.location=document.referrer;
		//可以获取前一页面的URL地址的方法,并返回上一页。
	    }, false); 
	pushHistory();
}

function pushHistory() {  
var state = {  
    title: "title",  
    url: "#"  
};  
window.history.replaceState(state, "title", "#");  
}
/* ios 回退时，加载中无法隐藏 bug 20170417 end*/